// 文件路径: frontend/static/js/user_management.js
// 功能说明:
//   该文件包含用户管理页面的JavaScript逻辑，包括加载用户列表、创建用户、编辑用户、删除用户等功能。
// 使用说明:
//   该文件通过与后端API交互，执行用户的增删改查操作。

// 动态加载角色复选框列表
function loadRoleOptions(selectedRoles) {
  fetch('/api/admin/roles', {
    headers: {
      'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
    }
  })
    .then(res => res.json())
    .then(data => {
      const group = document.getElementById('roleCheckboxGroup');
      if (!group) return;
      group.innerHTML = '';
      if (data.success && Array.isArray(data.data)) {
        data.data.forEach(role => {
          const label = document.createElement('label');
          label.className = 'checkbox-inline mr-3';
          const checkbox = document.createElement('input');
          checkbox.type = 'checkbox';
          checkbox.name = 'role';
          checkbox.value = role.name;
          if (selectedRoles && selectedRoles.includes(role.name)) checkbox.checked = true;
          label.appendChild(checkbox);
          label.appendChild(document.createTextNode(' ' + role.name));
          group.appendChild(label);
        });
      }
    })
    .catch(err => {
      console.error('加载角色选项失败:', err);
    });
}

// 加载用户列表
function loadUserList() {
  fetch('/api/users', {
    headers: {
      'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
    }
  })
    .then(response => {
      if (!response.ok) throw new Error('加载失败: ' + response.status);
      return response.json();
    })
    .then(response => {
      console.log('获取用户列表响应:', response);  // 调试日志
      
      // 检查响应格式
      if (!response.success) {
        throw new Error(response.message || '获取用户列表失败');
      }
      
      const users = response.data || [];
      console.log('用户数据:', users);  // 调试日志
      
      const userList = document.getElementById('userList');
      userList.innerHTML = users.map(user => {
        let roles = '';
        if (Array.isArray(user.roles)) {
          roles = user.roles.join(', ');
        } else if (user.role) {
          roles = user.role;
        }
        return `
        <tr>
          <td>${user.username || ''}</td>
          <td>${roles}</td>
          <td>${user.status || 'active'}</td>
          <td>
            <button class="btn btn-sm btn-warning" onclick="editUser(${user.id})">编辑</button>
            <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
            <button class="btn btn-sm btn-info" onclick="viewUserLog(${user.id})">日志</button>
          </td>
        </tr>
        `;
      }).join('');
    })
    .catch(error => {
      console.error('加载用户列表错误:', error);
      // 显示错误信息给用户
      const userList = document.getElementById('userList');
      userList.innerHTML = `<tr><td colspan="4" class="text-center text-danger">加载用户列表失败: ${error.message}</td></tr>`;
    });
}
// 初始化
document.addEventListener("DOMContentLoaded", function () {
  // 页面加载自动拉取用户列表
  loadUserList();
  loadRoleOptions([]);

  // 复用表单弹窗
  const userFormModal = document.getElementById("userFormModal");
  const userFormTitle = document.getElementById("userFormTitle");
  const userFormElement = document.getElementById("userFormElement");
  const userFormSubmitBtn = document.getElementById("userFormSubmitBtn");
  const userFormCancelBtn = document.getElementById("userFormCancelBtn");
  const editUserIdInput = document.getElementById("editUserId");
  const createUserBtn = document.getElementById("createUserBtn");

  // 打开创建用户弹窗
  createUserBtn.addEventListener("click", function () {
    userFormTitle.textContent = "创建新用户";
    userFormSubmitBtn.textContent = "创建";
    editUserIdInput.value = "";
    userFormElement.reset();
    loadRoleOptions([]); // 新建时刷新角色选项
    userFormModal.style.display = "block";
  });

  // 取消按钮
  userFormCancelBtn.addEventListener("click", function () {
    userFormModal.style.display = "none";
  });

  // 表单提交处理（创建或编辑）
  userFormElement.addEventListener("submit", function (e) {
    e.preventDefault();
    const userId = editUserIdInput.value;
    const formData = {
      username: document.getElementById("username").value,
      password: document.getElementById("password").value,
      roles: Array.from(document.querySelectorAll('input[name="role"]:checked')).map(cb => cb.value)
    };
    let url, method;
    if (userId) {
      // 编辑
      url = `/api/users/edit/${userId}`;
      method = "PUT";
      if (!formData.password) delete formData.password; // 不修改密码时不传
    } else {
      // 创建
      url = "/api/users/create";
      method = "POST";
    }
    fetch(url, {
      method: method,
      headers: { 
        "Content-Type": "application/json",
        'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
      },
      body: JSON.stringify(formData),
    })
      .then((response) => {
        if (!response.ok) throw new Error("HTTP错误: " + response.status);
        return response.json();
      })
      .then((data) => {
        if (data.success) {
        alert(data.message || "操作成功");
        userFormModal.style.display = "none";
        loadUserList();
        } else {
          alert(data.message || "操作失败");
        }
      })
      .catch((error) => {
        alert("操作失败: " + error.message);
      });
  });
});
// 删除用户
window.deleteUser = function (userId) {
  if (confirm(`确定要删除用户ID ${userId} 吗？`)) {
    fetch(`/api/users/delete/${userId}`, {
      method: "DELETE",
      headers: {
        'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
      }
    })
      .then((response) => {
        if (!response.ok) throw response;
        return response.json();
      })
      .then((data) => {
        if (data.success) {
          alert(data.message || "删除成功");
        loadUserList();
        } else {
          alert(data.message || "删除失败");
        }
      })
      .catch((error) => {
        if (error.json) {
          error.json().then((err) => alert(err.message || "删除失败"));
        } else {
          alert("删除失败: " + error.message);
        }
      });
  }
};

// 编辑用户
window.editUser = function (userId) {
  // 编辑用户：弹窗并填充表单
  fetch(`/api/users/${userId}`, {
    headers: {
      'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
    }
  })
    .then((response) => {
      if (!response.ok) throw new Error('获取用户信息失败: ' + response.status);
      return response.json();
    })
    .then((response) => {
      if (!response.success) {
        throw new Error(response.message || '获取用户信息失败');
      }
      const user = response.data;
      document.getElementById("username").value = user.username || "";
      // 支持多角色
      let userRoles = [];
      if (Array.isArray(user.roles)) {
        userRoles = user.roles;
      } else if (user.role) {
        userRoles = [user.role];
      }
      loadRoleOptions(userRoles);
      document.getElementById("password").value = ""; // 不显示原密码
      document.getElementById("editUserId").value = user.id;
      userFormTitle.textContent = "编辑用户";
      userFormSubmitBtn.textContent = "保存";
      userFormModal.style.display = "block";
    })
    .catch((error) => alert("获取用户信息失败: " + error.message));
};

// 增加系统日志按钮事件
const viewSystemLogBtn = document.getElementById("viewSystemLogBtn");
if (viewSystemLogBtn) {
  viewSystemLogBtn.addEventListener("click", function () {
    fetch("/api/system-logs", {
      headers: {
        'Authorization': 'Bearer ' + (localStorage.getItem('access_token') || '')
      }
    })
      .then((response) => {
        if (!response.ok) throw new Error('获取系统日志失败: ' + response.status);
        return response.json();
      })
      .then((response) => {
        if (response.success) {
          alert(JSON.stringify(response.data || [], null, 2));
        } else {
          alert(response.message || '获取系统日志失败');
        }
      })
      .catch((error) => alert("获取系统日志失败: " + error.message));
  });
}

// 查看单个用户日志

// 获取JWT Token
function getToken() {
  return localStorage.getItem('access_token') || sessionStorage.getItem('access_token') || '';
}

window.viewUserLog = function(userId) {
  const token = getToken();
  if (!token) {
    if (window.Swal) {
      Swal.fire('提示', '未检测到登录凭证，请重新登录后再试。', 'warning');
    } else {
    alert('未检测到登录凭证，请重新登录后再试。');
    }
    return;
  }
  
  // 使用统一日志系统查询用户操作日志
  fetch(`/api/admin/logs?target_id=${userId}&action=UPDATE,CREATE,DELETE`, {
    headers: {
      'Authorization': 'Bearer ' + token,
      'Content-Type': 'application/json'
    }
  })
    .then((response) => {
      if (response.status === 401) throw new Error('未认证或Token无效');
      return response.json();
    })
    .then((data) => {
      if (data.success && data.data && data.data.length > 0) {
        // Format logs for display
        let html = data.data
          .map((log) => {
            let localTime = log.operation_time
              ? new Date(log.operation_time).toLocaleString()
              : "";
            let restoreButton = "";

            // 根据日志类型显示不同的恢复按钮
            const actionLower = log.action.toLowerCase();
            if (actionLower === "delete") {
              restoreButton = `<button class="btn btn-sm btn-outline-success mt-2" onclick="restoreUserLog(${log.id})">恢复已删除用户</button>`;
            } else if (actionLower === "restore") {
              restoreButton = `<span class="badge bg-info mt-2">恢复操作记录</span>`;
            } else if (
              log.old_content &&
              (actionLower === "create" || actionLower === "update")
            ) {
              restoreButton = `<button class="btn btn-sm btn-outline-primary mt-2" onclick="restoreUserLog(${log.id})">恢复此版本</button>`;
            }

            return `<div style="border-bottom:1px solid #eee;margin-bottom:12px;padding-bottom:8px;">
              <div><strong>操作类型：</strong>${log.action} | <strong>操作人：</strong>${log.operator || '系统'} | <strong>时间：</strong>${localTime}</div>
              ${log.new_content ? `<div><strong>当前内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#e8f5e8;padding:8px;border-radius:4px;border-left:4px solid #28a745;">${log.new_content}</pre></div>` : ""}
              ${log.old_content ? `<div><strong>历史内容：</strong><pre style="white-space:pre-wrap;font-size:12px;max-height:120px;overflow-y:auto;background:#fff3cd;padding:8px;border-radius:4px;border-left:4px solid #ffc107;">${log.old_content}</pre>${restoreButton ? `<div style="margin-top:8px;">${restoreButton}</div>` : ""}</div>` : ""}
            </div>`;
          })
          .join("");

        if (window.Swal) {
          Swal.fire({
            title: '用户操作日志',
            html: `<div style="max-height:600px;overflow-y:auto;text-align:left;">${html}</div>`,
            width: 1000,
            showConfirmButton: false,
            showCloseButton: true,
          });
        } else {
          alert("日志功能需要引入 SweetAlert2 支持美观弹窗。");
        }
      } else {
        if (window.Swal) {
          Swal.fire("无日志", "该用户暂无操作日志", "info");
        } else {
          alert("该用户暂无操作日志");
        }
      }
    })
    .catch((error) => {
      if (window.Swal) {
        Swal.fire("获取日志失败", "网络错误：" + error.message, "error");
      } else {
        alert("获取用户日志失败: " + error.message);
      }
    });
};

// 恢复用户日志
window.restoreUserLog = function(logId) {
    const token = getToken();
    if (!token) {
        if (window.Swal) {
            Swal.fire('提示', '未检测到登录凭证，请重新登录后再试。', 'warning');
        } else {
            alert('未检测到登录凭证，请重新登录后再试。');
        }
        return;
    }
    
    if (window.Swal) {
        Swal.fire({
            title: '确认恢复',
            text: '确定要恢复此版本的用户信息吗？',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: '确定恢复',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                performUserRestore(logId, token);
            }
        });
    } else {
        if (confirm('确定要恢复此版本的用户信息吗？')) {
            performUserRestore(logId, token);
        }
    }
};

// 执行用户恢复操作
function performUserRestore(logId, token) {
    fetch(`/api/admin/logs/${logId}/restore`, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (window.Swal) {
                Swal.fire('恢复成功', '用户信息已恢复到指定版本', 'success');
            } else {
                alert('恢复成功');
            }
            // 重新加载用户列表
            loadUserList();
        } else {
            if (window.Swal) {
                Swal.fire('恢复失败', data.message || '恢复操作失败', 'error');
            } else {
                alert('恢复失败: ' + (data.message || '恢复操作失败'));
            }
        }
    })
    .catch(error => {
        if (window.Swal) {
            Swal.fire('恢复失败', '网络错误：' + error.message, 'error');
        } else {
            alert('恢复失败: ' + error.message);
        }
    });
}
